import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.basic.exception.GlobalException;
import com.basic.pojo.MyTableFieldInfo;
import com.basic.service.dto.GenParam;
import com.basic.service.impl.MyGenServiceImpl;
import com.basic.utils.GenUtil;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class JavaClassGenerator {
    public static void main(String[] args) throws IllegalAccessException {
//        test2();
//        System.out.println(GenParam.getClassName("user_info"));
//        String test = "COLUMN_NAME";
//        System.out.println(StrUtil.toCamelCase(test.toLowerCase()));
        test2();
    }


    public static void test3() {

    }

    public static void test2() throws IllegalAccessException {

        String driverClass = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://192.168.1.85:3306/blog?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=GMT%2B8";
        String username = "root";
        String passwd = "dd@123";
        JdbcTemplate jdbcTemplate = GenUtil.createJdbcTemplate(driverClass, url, username, passwd);

        String tableName = "comment";
        Map<String, GenParam.TableInfo> allDataForDatasource = GenUtil.getAllDataForDatasource(jdbcTemplate, Arrays.asList(tableName), GenUtil.getDatabaseNameForUrl(url));

        MyGenServiceImpl myGenService = new MyGenServiceImpl();


        GenParam.TableInfo tableInfo = allDataForDatasource.get(tableName);

        if (ObjectUtil.isEmpty(tableInfo)) {
            throw new GlobalException("获取数据失败");
        }

        final GenParam genParam = GenParam.builder()
                .controllerPath("/" + tableInfo.getClassNameSmall())
                .tableInfo(tableInfo)
                .author("cjy")
                .module("demo")
                .packagePath("com.cjy")
                .type(GenParam.Type.POJO.getVal())
                .createTime(DateUtil.format(new Date(), "yyyy-MM-dd"))
                .tableInfoList(Arrays.asList(tableInfo))
                .build();

        final List<StringWriter> projectStringWriter = new ArrayList<>();
        GenParam.Type[] values = GenParam.Type.values();
//        List<GenParam.Type> values = new ArrayList<>();
//        values.add(GenParam.Type.CONTROLLER);
//        values.add(GenParam.Type.POJO);

        try (FileOutputStream fos = new FileOutputStream(
                "E:\\mycode\\basic-project\\basic-project\\generate\\src\\main\\resources\\file\\"
                        + genParam.getZipFileName());
             ZipOutputStream zipOutputStream = new ZipOutputStream(fos)) {

            for (GenParam.Type each : values) {
                genParam.setType(each.getVal());
                myGenService.genZip(zipOutputStream, myGenService.genCodeForVelocityContext(genParam).toString(), genParam);
            }

            zipOutputStream.closeEntry();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void test1() throws IllegalAccessException {
        // 初始化 Velocity 引擎
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.init();

        // 加载模板
        Template template = velocityEngine.getTemplate("vm/java/controller.java.vm");

        final GenParam genParam = GenParam.builder()
                .controllerPath("/" + StrUtil.toUnderlineCase("User"))
                .author("cjy")
                .module("demo")
                .packagePath("com.cjy")
                .type(GenParam.Type.POJO.getVal())
                .build();

        // 创建上下文并填充数据
        VelocityContext velocityContext = GenUtil.createVelocityContextForClass(genParam);


        // 合并模板和上下文并生成 Java 类代码
        StringWriter stringWriter = new StringWriter();
        template.merge(velocityContext, stringWriter);
        String javaClassCode = stringWriter.toString();

        // 输出生成的 Java 类代码到控制台（可选）
        System.out.println(javaClassCode);
        String module = "demo";

//         创建 ZIP 文件并写入生成的 Java 类代码
        try (FileOutputStream fos = new FileOutputStream("E:\\mycode\\basic-project\\basic-project\\generate\\src\\main\\resources\\file\\" + module + "zip");
             ZipOutputStream zipOutputStream = new ZipOutputStream(fos)) {

            ZipEntry zipEntry = new ZipEntry("class/MyClass.java");
            zipOutputStream.putNextEntry(zipEntry);
            zipOutputStream.write(javaClassCode.getBytes());
            zipOutputStream.closeEntry();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}